const socket = io.connect();

const loginname = document.querySelector(".loginname");
console.log("登录用户名: " + loginname.innerText);
const sub = document.querySelector('#sub');
const mContent = document.querySelector("#mContent");
const messages = document.querySelector("#messages");
const clear = document.querySelector("#clear");

sub.addEventListener('click', (event) => {
    event.preventDefault();
    sendMsg();
});

clear.addEventListener('click', event => {
    event.preventDefault();
    alert('当前功能还未开发');
});

if (loginname.innerText) {
    let imgN = Math.floor(Math.random() * 4) + 1; // 随机分配头像
    socket.emit('login', {
        name: loginname.innerText,
        img: 'images/user' + imgN + '.jpg'
    }); // 触发登录事件
}


// 显示在线人员
socket.on('disUser', (usersInfo) => {
    console.log(usersInfo);

    displayUser(usersInfo);
});


// 显示在线人员
function displayUser(users) {
    const user = document.querySelector("#users");
    const num = document.querySelector('#num');
    const contactp = document.querySelector('.contacts p');
    // 每次都要重新渲染
    user.innerText = '';
    if (!users.length) {
        contactp.style.display = "block";
    } else {
        contactp.style.display = "none";
    }
    num.innerText = users.length;
    // $('#num').text(users.length);
    for (var i = 0; i < users.length; i++) {
        let elem_li = document.createElement('li');
        let html = `<img src="${users[i].img}">
        <span>${users[i].name}</span>`;
        elem_li.innerHTML = html;
        console.log(users[i].img);
        user.appendChild(elem_li);
    }
}


// 接收消息
socket.on('receiveMsg', (obj) => {
    var msg = obj.msg;
    var content = '';
    console.log(msg);

    content += '<span>' + msg + '</span>';
    let mess_li = document.createElement('li');
    mess_li.className = `${obj.side}`;
    console.log(`${ obj.img }`);

    let html = `
          <img src="${obj.img}">
          <div>
            <span>${obj.name}</span> <span>${obj.date}</span>
            <p style="color: ${obj.color};">${content}</p>
          </div>
      `;
    mess_li.innerHTML = html;
    messages.appendChild(mess_li);
    // 滚动条总是在最底部
    messages.scrollTop = messages.scrollHeight
});


// 发送消息
var color = '#000000';

function sendMsg() {
    if (mContent.value == '') {
        alert('请输入内容！');
        return false;
    }
    socket.emit('sendMsg', {
        name: loginname.innerText,
        msg: mContent.value,
        color: color,
        type: 'text'
    });
    mContent.value = '';
    return false;
}